window.onload = function () {
    /* console.log(document.getElementById("ad1"))*/
    // document.getElementById("ad1").addEventListener("change", changeevent, false);

    //var sta_l = 1;

    /*function changeevent() {
        var input = this;
        console.log(this)
        if (input.files && input.files[0]) {

            var reader = new FileReader();
            reader.onload = function (e) {
                var la = document.querySelector('label[for="' + input.id + '"]');
                /!*console.log(la)*!/
                la.getElementsByTagName('img')[0].src = e.target.result;
                la.getElementsByTagName('img')[0].classList.add("k");
                la.getElementsByTagName('p')[0].classList.add("d");
                laload();
            }
            reader.readAsDataURL(input.files[0]);

        }
    }*/

    /*function laload() {
        sta_l++;
        if (sta_l > 1) {
            $('.photo .exp').hide();
        }
        if (sta_l > 5) {
            return;
        }
        var inc = document.createElement("input");
        inc.type = "file";
        inc.name = "headPic";
        inc.accept = "image/!*";
        inc.id = "ad" + sta_l;
        inc.classList.add("d");
        var lab = document.createElement("label");
        lab.setAttribute("for", "ad" + sta_l);
        var dc = document.getElementById('box');
        var imgs = document.createElement("img");
        imgs.classList.add("d");
        var pc = document.createElement("p");
        pc.classList.add("f");
        console.log([lab]);
        dc.appendChild(inc);
        lab.appendChild(imgs);
        lab.appendChild(pc);

        dc.appendChild(lab);
        inc.addEventListener("change", changeevent, false);
    }*/


    /*二次上传图片*/

    var img = []; //创建一个空对象用来保存传入的图片
    var AllowImgFileSize = '1024'; //1兆
    $("#inputs").on('change', function () {

        /*var filePath = $(this).val(),         //获取到input的value，里面是文件的路径
            fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
            imgBase64 = '',      //存储图片的imgBase64
            fileObj = document.getElementById('inputs').files[0]; //上传文件的对象,要这样写才行，用jquery写法获取不到对象
        // 检查是否是图片
        if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
            alert('上传错误,文件格式必须为：png/jpg/jpeg');
            return;
        }
        console.log(fileFormat);*/


        var fil = this.files;
        for (var i = 0; i < fil.length; i++) {
            var curr = $('#inputs')[i].files[0].size;


            reads(fil[i]);
            img.push($('#inputs')[i].files[0]); //将传入的图片push到空对象中
            console.log(img);

            /*if (curr > AllowImgFileSize * 1024) { //当图片大于1兆提示
                alert("图片文件大小超过限制 请上传小于1M的文件");
            } else {
                reads(fil[i]);
                img.push($('#inputs')[i].files[0]); //将传入的图片push到空对象中
                console.log(img)
            }*/
        }


        // 调用函数，对图片进行压缩
        /*compress(fileObj, function (imgBase64) {
           // console.log(imgBase64);

            imgBase64 = imgBase64;    //存储转换的base64编码
            $('.imgBiMG').attr('src', imgBase64); //显示预览图片
        });*/


        if (img.length >= 1) {
            $(".productDrawingBox .exp").hide();
        }
        if (img.length >= 5) { //判断图片的数量，数量不能超过5张
            $('.uploadDIv').hide();
        } else {
            $('.uploadDIv').show();
        }
        console.log(img);
    });

    function reads(fil) {
        var reader = new FileReader();
        reader.readAsDataURL(fil);


        reader.onload = function () {
            document.getElementById("uploadBox").innerHTML += "<div class='divImg' id='uploadImg'><img src='" + reader.result + "' class='imgBiMG' ></div>";
        }
    }


    //故障原因选项
    $('.fault .fault_option span').click(function () {
        if ($(this).hasClass('span_001')) {
            $(this).removeClass('span_001');
        } else {
            $(this).addClass('span_001');

        }
    });


    $('.button_01 .infor_sub').click(function () {


        var IMEI = $.trim($(".content .ipt .IMEI").val()); //IMEI
        var IMEI_top = $(".content .ipt .IMEI").offset().top;

        var color = $.trim($(".content .ipt .color").val());  //设备颜色
        var color_top = $(".content .ipt .color").offset().top;

        var name = $.trim($(".content .ipt .name").val()); //名字
        var name_top = $(".content .ipt .name").offset().top;

        var phone = $.trim($(".content .ipt .phone").val()); //手机号
        var phone_top = $(".content .ipt .phone").offset().top;

        var address = $.trim($(".content .ipt .address").val()); //收货地址


        var fault = $.trim($(".content .ipt .describe_fault").val()); //故障描述
        var file = $(".content .photo .insert").find('input'); //照片


        /*var checked = $(".agreement_box input[type='checkbox']").is(':checked'); //协议勾选*/


        if (file.files != undefined && file.files.size() > 0) {
            var picFileSize = file.files[0].size / 1024;
            if (file.files[0].size / 1024 > 500) {
                alert("文件大小不能超过500Kb");
                return;
            }
        }
        //验证照片是否为空
        /*if (file.val().length==0) {
            alert("请上传照片！");
            return;

        }*/


        if (IMEI == '') {
            alert('请输入IMEI号');
            $(document).scrollTop(IMEI_top);
            $(".content .ipt .IMEI").focus();
            $input();

            return;
        }
        if (!(/^[0-9]{15}$/.test(IMEI))) {
            $(document).scrollTop(IMEI_top);
            $(".content .ipt .IMEI").focus();
            $input();
            alert('请输入正确的15位IMEI号');
            return;
        }
        if (color == '') {
            $(document).scrollTop(color_top);
            $(".content .ipt .color").focus();
            $input();
            alert('请输入手表颜色');
            return;
        }

        if (name == '') {
            $(document).scrollTop(name_top);
            $(".content .ipt .name").focus();
            $input();
            alert('请输入联系人姓名');
            return;
        }
        if (!checkPhone(phone)){
            $(".content .ipt .phone").focus();
            $input();
            alert("手机号码有误，请重填");
            return false;
        }


        if (address == '') {
            $(".content .ipt .address").focus();
            alert('请输入收货地址');
            return;
        }
        if (fault == '') {
            $(".content .ipt .describe_fault").focus();
            alert('请简要描述具体故障原因');
            return;
        }


        /*获取里边的所有要上传的值*/
        var postdata = $('#Submit_001').serialize();
        var fault = $('.fault .fault_option').children('.span_001');
        var fault_le = fault.length;
        var _data = [];
        for (var i = 0; i < fault_le; i++) {
            _data.push(fault.eq(i).text())

        }

        var breakdownReason = "breakdownReason=" + _data.join(',');

        var file = $('.photo .insert input[name="headPic"]').val();

        var file_999 = $('#inputs');
        var file2 = $('#inputs').val();

        console.log(file_999);
        console.log(file2);

        console.log(img);
        var formData = new FormData($("#Submit_001")[0]);
        let j = 1;
        for (let i of img) {
            formData.append("photo", i);
            j++;
        }

        console.log(formData);
        formData.forEach(function (k, v) {
            console.log(k, v)
        });


        //Loading
        var load = new Loading();
        load.init();


        console.log(postdata);
        $.ajax({
            url: "/systemSet/applyMaintain.html?" + breakdownReason,
            dataType: "json",
            type: "post",

            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                load.start();
            },
            success: function (data) {
                console.log(data);
                if (data.code != 1) {
                    console.log(data.msg);
                    load.stop();
                    return;
                }
                load.stop();
                alert('提交成功！');
                window.location.reload();
            },
            error: function (e) {
                console.log(e);
                console.log("出错了");
            }

        })


    })


}

function $input() {
    $(".content .ipt input").focus(function () {
        $(this).addClass("input_002");
    });

    $('.content .ipt input').blur(function () {
        $(this).removeClass("input_002");
    });
}






//图片处理

// 不对图片进行压缩，直接转成base64
/*function directTurnIntoBase64(fileObj, callback) {
    var r = new FileReader();        // 转成base64
    r.onload = function () {
        //变成字符串
        imgBase64 = r.result;
        console.log(imgBase64);
        callback(imgBase64);
    }
    r.readAsDataURL(fileObj);    //转成Base64格式
}        // 对图片进行压缩
function compress(fileObj, callback) {
    if (typeof (FileReader) === 'undefined') {
        console.log("当前浏览器内核不支持base64图标压缩");              //调用上传方式不压缩
        directTurnIntoBase64(fileObj, callback);
    } else {
        try {
            var reader = new FileReader();
            reader.onload = function (e) {
                var image = $('<img/>');
                image.load(function () {
                    square = 300,   //定义画布的大小，也就是图片压缩之后的像素
                        canvas = document.createElement('canvas'),
                        context = canvas.getContext('2d'),
                        imageWidth = 0,    //压缩图片的大小
                        imageHeight = 0,
                        offsetX = 0,
                        offsetY = 0,
                        data = '';
                    canvas.width = square;
                    canvas.height = square;
                    context.clearRect(0, 0, square, square);
                    if (this.width > this.height) {
                        imageWidth = Math.round(square * this.width / this.height);
                        imageHeight = square;
                        offsetX = -Math.round((imageWidth - square) / 2);
                    } else {
                        imageHeight = Math.round(square * this.height / this.width);
                        imageWidth = square;
                        offsetY = -Math.round((imageHeight - square) / 2);
                    }
                    context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                    var data = canvas.toDataURL('image/jpeg');                          //压缩完成执行回调
                    callback(data);
                });
                image.attr('src', e.target.result);
            };
            reader.readAsDataURL(fileObj);
        } catch (e) {
            console.log("压缩失败!");                  //调用直接上传方式  不压缩
            directTurnIntoBase64(fileObj, callback);
        }
    }

}*/


